package com.rc.saas.mini.controller.activity;

import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.constant.SessionConstants;
import com.rc.saas.mini.mapper.market.MarketActivityMemberMapper;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.market.MarketActivity;
import com.rc.saas.mini.model.market.MarketActivityMember;
import com.rc.saas.mini.model.market.MarketActivityMemberExample;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.service.market.MarketActivityService;
import com.rc.saas.mini.service.market.MarketActivityServiceImpl;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.vo.market.MarketActivityVo2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Api(tags = "26.活动相关")
@Controller
@RequestMapping("/activity")
public class ActivityController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(ActivityController.class);

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MarketActivityService marketActivityService;

    @Autowired
    private MarketActivityMemberMapper marketActivityMemberMapper;
    @Autowired
    private MarketActivityServiceImpl marketActivityServiceImpl;

    @ResponseBody
    @RequestMapping(value = "/open/listActivityRuleWithGive", method = RequestMethod.POST)
    @ApiOperation(value = "活动规则列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "activityIndex", paramType = "query", value = "活动位置(0:首页 1活动中心 默认0", required = false)})
    public DataTResponse<List<MarketActivityVo2>> listActivityRuleWithGive(HttpServletRequest request
            , @RequestParam(value = "activityIndex", defaultValue = "0") String activityIndex) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        //Tenant tenant = tenantService.selectByTenantCode(tenantCode);
        LoginInfoVo loginInfo = readLoginInfo(request);

        MemberInfo member = new MemberInfo();
        if (loginInfo != null && loginInfo.getMemberId() != null) {
            member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        }
        if ("".equals(activityIndex)) {
            activityIndex = null;
        }
        //互联互通用户不能参与活动
        if ("3".equals(member.getMemberType())) {
            return DataTResponse.SUCCESS();
        }
        if(member==null){
            return DataTResponse.SUCCESS();
        }
        List<MarketActivityVo2> listActivityRule =
                marketActivityService.listActivityRuleWithGive(activityIndex, tenantCode, member.getMemberId());
        if (listActivityRule != null) {
            for (MarketActivityVo2 marketActivityVo2 : listActivityRule) {
                if (marketActivityVo2.getContent() != null &&
                        marketActivityVo2.getContent().indexOf("<img src=\"") >= 0) {
                    int s = marketActivityVo2.getContent().indexOf("<img src=\"");
                    String data = marketActivityVo2.getContent().substring(s, marketActivityVo2.getContent().indexOf("\"", s));
                    marketActivityVo2.setContentImg(data);
                }

            }
        }

        return DataTResponse.SUCCESS_DATA(listActivityRule);
    }

    @ResponseBody
    @RequestMapping(value = "/selectByMarketActivityId", method = RequestMethod.POST)
    @ApiOperation(value = "活动byId", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "marketActivityId", paramType = "query", value = "活动ID", required = true)
    })
    public DataTResponse<MarketActivityVo2> selectByMarketActivityId(HttpServletRequest request
            , Long marketActivityId) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        //Tenant tenant = tenantService.selectByTenantCode(tenantCode);
        LoginInfoVo loginInfo = readLoginInfo(request);

        MemberInfo member = new MemberInfo();
        if (loginInfo != null && loginInfo.getMemberId() != null) {
            member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        }

        List<MarketActivityVo2> listActivityRule =
                marketActivityService.listActivityRuleWithGive(null, tenantCode, member.getMemberId());
        if (listActivityRule != null) {
            for (MarketActivityVo2 marketActivityVo2 : listActivityRule) {
                if (marketActivityVo2.getContent() != null &&
                        marketActivityVo2.getContent().indexOf("<img src=\"") >= 0) {
                    int s = marketActivityVo2.getContent().indexOf("<img src=\"");
                    String data = marketActivityVo2.getContent().substring(s, marketActivityVo2.getContent().indexOf("\"", s));
                    marketActivityVo2.setContentImg(data);
                }

            }
        }

        return DataTResponse.SUCCESS_DATA(listActivityRule.stream().filter(data->marketActivityId.equals(data.getMarketActivityId())).findFirst().orElseGet(()->null));
    }

    @ResponseBody
    @RequestMapping(value = "/giveActivityById", method = RequestMethod.POST)
    @ApiOperation(value = "点击参与活动", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "marketActivityId", paramType = "query", value = "活动ID", required = true)
    })
    public DataTResponse<String> giveActivityById(HttpServletRequest request, Long marketActivityId) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        //Tenant tenant = tenantService.selectByTenantCode(tenantCode);
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        MarketActivity marketActivity = marketActivityService.selectByPrimaryKey(marketActivityId);
        if (marketActivity == null) {
            return DataTResponse.FAIL("活动不存在");
        }
        MarketActivityMemberExample marketActivityMemberExample = new MarketActivityMemberExample();
        marketActivityMemberExample.createCriteria().andMarketActivityIdEqualTo(marketActivityId).andMemberIdEqualTo(member.getMemberId());
        MarketActivityMember marketActivityMember = marketActivityMemberMapper.selectByExample(marketActivityMemberExample).stream().findFirst().orElseGet(() -> null);
        if (marketActivityMember == null) {
            //activity_type      enum ('0', '1', '2', '3', '4', '5', '6') default '1' not null comment '活动类型 0 新用户注册优惠 1 充值送活动默认 2领取活动 3满减 4满返 5拉新  默认1充值',
            // @ApiModelProperty(value = "活动类型 0 新用户注册优惠 1 充值送活动默认 2领取活动 3满减 4满返 5拉新  默认1充值")
            marketActivityServiceImpl.marketActivityMemberAdd2(member, marketActivityId, null, marketActivity.getActivityType());
        }

        return DataTResponse.SUCCESS();
    }
}
